<template>
    <view class="add-form-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header :title="isEdit ? '编辑农资入库' : '新增农资入库'"></page-header>

        <view class="basic-info">
            <view class="section-title">基础信息</view>

            <uni-forms
                ref="form"
                :modelValue="formData"
                :rules="rules"
                validateTrigger="bind"
                label-position="top"
                class="farm-form"
                label-width="200px">
                <uni-forms-item label="入库时间" name="inDate" required>
                    <uni-datetime-picker
                        type="date"
                        v-model="formData.inDate"
                        :border="false"
                        :label-width="200"
                        @change="dateChange">
                        <view class="uni-date-picker-container">
                            <text
                                :class="{
                                    placeholder: !formData.inDateText,
                                }">
                                {{ formData.inDateText || '请选择入库时间' }}
                            </text>
                            <view class="date-icon">
                                <roc-icon-plus
                                    type="fas"
                                    name="calendar-alt"
                                    :size="18"
                                    color="#999"></roc-icon-plus>
                            </view>
                        </view>
                    </uni-datetime-picker>
                </uni-forms-item>

                <uni-forms-item label="仓库名称" name="warehouseId" required>
                    <uni-data-select
                        v-model="formData.warehouseId"
                        :localdata="warehouseNamesData"
                        placeholder="请选择仓库名称"
                        @change="onWarehouseChange"></uni-data-select>
                </uni-forms-item>

                <uni-forms-item label="仓库位置" name="locationId" required>
                    <uni-data-select
                        v-model="formData.locationId"
                        :localdata="warehouseLocationsData"
                        placeholder="请选择仓库位置"
                        @change="handleLocationChange"></uni-data-select>
                </uni-forms-item>
                <uni-forms-item label="农资类型" name="materialId" required>
                    <uni-data-select
                        v-model="formData.materialId"
                        :localdata="currentAgriculturalTypesData"
                        placeholder="请选择农资类型"
                        :disabled="!formData.locationId"></uni-data-select>
                </uni-forms-item>
                <uni-forms-item label="规格" name="specId" required>
                    <uni-data-select
                        v-model="formData.specId"
                        :localdata="specificationData"
                        placeholder="请选择规格"></uni-data-select>
                </uni-forms-item>

                <uni-forms-item label="数量" name="quantity" required>
                    <uni-easyinput
                        type="digit"
                        v-model="formData.quantity"
                        placeholder="请输入数量"
                        @input="calculateTotalAmount"></uni-easyinput>
                </uni-forms-item>
                <uni-forms-item label="来源" name="procurementMethod" required>
                    <view class="radio-group">
                        <view
                            v-for="type in procurementMethodData"
                            :key="type.value"
                            class="radio-item"
                            @click="formData.procurementMethod = type.value">
                            <view
                                class="radio-circle"
                                :class="{ active: formData.procurementMethod === type.value }">
                                <view
                                    class="radio-inner"
                                    v-if="formData.procurementMethod === type.value"></view>
                            </view>
                            <text class="radio-label">{{ type.text }}</text>
                        </view>
                    </view>
                </uni-forms-item>
                <uni-forms-item label="厂商" name="supplier">
                    <uni-easyinput
                        v-model="formData.supplier"
                        placeholder="请输入厂商"></uni-easyinput>
                </uni-forms-item>
                <uni-forms-item label="备注" name="remark">
                    <uni-easyinput
                        v-model="formData.remark"
                        placeholder="请输入备注信息"
                        type="textarea"
                        :maxlength="200"></uni-easyinput>
                </uni-forms-item>
            </uni-forms>
        </view>

        <view class="photo-section">
            <view class="section-title">图片上传</view>
            <image-uploader ref="imageUploader" :images="formData.images" :maxCount="9" />
        </view>

        <view class="submit-btn-container">
            <view class="submit-btn" @click="submitForm">确认提交</view>
        </view>
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'
import ImageUploader from '@/components/ImageUploader/index.vue'
import { formatDate, getDefaultDateRange } from '@/utils/util.js'
import { mapGetters, mapActions } from 'vuex'
// 导入API
import { warehouse } from '@/utils/api/index.js'

export default {
    components: {
        PageHeader,
        ImageUploader,
    },
    data() {
        return {
            isEdit: false,
            editId: null,
            formData: {
                inDate: '',
                inDateText: '',
                warehouseId: '', // 仓库ID
                locationId: '', // 库位ID
                quantity: '',
                unit: '',
                source: '',
                manufacturer: '',
                remark: '',
                images: [],
                // 接口所需字段
                materialId: '', // 默认农资ID
                specId:'', // 默认规格ID，可根据specification设置
                unitPrice: 0, // 单价
                totalAmount: 0, // 总金额
                batchNumber: '', // 批次号
                supplier: '', // 厂商
                operator: '', // 操作人
                procurementMethod: '', // 来源
            },
            rules: {
                inDate: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请选择入库时间',
                        },
                    ],
                },
                materialId: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请选择农资类型',
                        },
                    ],
                },
                warehouseId: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请选择仓库名称',
                        },
                    ],
                },
                locationId: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请选择仓库位置',
                        },
                    ],
                },
                specId: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请输入规格',
                        },
                    ],
                },
                quantity: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请输入数量',
                        },
                        {
                            format: 'number',
                            errorMessage: '请输入有效的数字',
                        },
                    ],
                },
                procurementMethod: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请选择来源',
                        },
                    ],
                },
                unitPrice: {
                    rules: [
                        {
                            required: true,
                            errorMessage: '请输入单价',
                        },
                        {
                            format: 'number',
                            errorMessage: '请输入有效的数字',
                        },
                    ],
                },
            },
            warehouseLocationsData: [], // 仓库位置数据（父级）
            currentAgriculturalTypesData: [], // 当前选中仓库位置的农资类型数据（子级）
            specificationData: [], // 规格数据
            warehouseNamesData: [], // 仓库名称数据
            unitsData: [], // 单位数据
            procurementMethodData: [], // 来源数据
        }
    },
    computed: {
        ...mapGetters({
            getDictByType: 'getDictByType',
            getDictLabel: 'getDictLabel',
            getWarehouseSelectData: 'getWarehouseSelectData',
        }),
    },
    async onLoad(options) {
        // 加载字典数据
        await this.loadDictData()

        // 设置默认日期为今天
        const today = new Date()
        this.formData.inDate = today.toISOString().split('T')[0]
        this.formData.inDateText = formatDate(today)

        if (options.id) {
            this.isEdit = true
            this.editId = parseInt(options.id)
            this.loadWarehouseData(this.editId)
        }
    },
    methods: {
        ...mapActions(['getDictByType', 'fetchWarehouseData']),

        // 加载字典数据
        async loadDictData() {
            try {
                uni.showLoading({ title: '加载数据...' })

                // 加载仓库位置字典（父级）
                await this.getDictByType('category')
                this.warehouseLocationsData = this.formatDictToSelectData('category')

                // 如果字典数据为空，使用默认数据
                if (this.warehouseLocationsData.length === 0) {
                    this.warehouseLocationsData = [
                        { value: 'fertilizer', text: '复合肥料' },
                    ]
                }

                // 加载规格单位字典
                await this.getDictByType('spec_unit')
                this.specificationData = this.formatDictToSelectData('spec_unit')

                // 如果规格字典数据为空，使用默认数据
                if (this.specificationData.length === 0) {
                    this.specificationData = [
                        { value: '0', text: 'g/瓶' },
                    ]
                }
                
                // 加载来源字典
                await this.getDictByType('procurement_method')
                this.procurementMethodData = this.formatDictToSelectData('procurement_method')

                // 如果来源字典数据为空，使用默认数据
                if (this.procurementMethodData.length === 0) {
                    this.procurementMethodData = [
                        { value: '1', text: '采购' },
                        { value: '2', text: '自产' },
                        { value: '3', text: '调拨' },
                    ]
                }
                
                // 加载仓库数据
                await this.fetchWarehouseData()
                // 设置仓库下拉数据
                this.warehouseNamesData = this.getWarehouseSelectData

                // 加载单位数据
                this.unitsData = [
                    { value: 'bag', text: '袋' },
                ]

                uni.hideLoading()
            } catch (error) {
                console.error('加载数据失败:', error)
                uni.hideLoading()
                uni.showToast({
                    title: '加载数据失败',
                    icon: 'none',
                })
            }
        },



        // 将字典数据格式化为下拉选择框所需的格式
        formatDictToSelectData(dictType) {
            const dictList = this.getDictByType(dictType)
            return dictList.map((item) => ({
                value: item.value,
                text: item.label,
            }))
        },


        // 格式化图片字段，将字符串转为数组
        formatImages(images) {
            if (!images) return []
            if (typeof images === 'string') {
                if (images.includes(',')) {
                    return images.split(',')
                }
                return [images]
            }
            return Array.isArray(images) ? images : []
        },

        dateChange(e) {
            if (e) {
                const date = new Date(e)
                this.formData.inDateText = formatDate(date)
            } else {
                this.formData.inDateText = ''
            }
        },

        // 计算总金额
        calculateTotalAmount() {
            const quantity = parseFloat(this.formData.quantity) || 0
            const unitPrice = parseFloat(this.formData.unitPrice) || 0
            this.formData.totalAmount = (quantity * unitPrice).toFixed(2)
        },

        // 仓库位置选择变化处理
        async handleLocationChange() {
            // 根据选择的仓库位置，更新农资类型下拉选项
            if (this.formData.locationId) {
                try {
                    // 根据选中的仓库位置获取对应的农资类型字典
                    const locationValue = this.formData.locationId

                    // 从字典中获取对应的仓库位置值
                    const locationDict = this.getDictByType('category')
                    const selectedLocation = locationDict.find((item) => item.value === locationValue)

                    if (selectedLocation) {
                        // 加载对应的农资类型字典
                        await this.getDictByType(selectedLocation.value)
                        this.currentAgriculturalTypesData = this.formatDictToSelectData(selectedLocation.value)
                    } else {
                        this.currentAgriculturalTypesData = []
                    }
                } catch (error) {
                    console.error('获取农资类型字典失败:', error)
                    this.currentAgriculturalTypesData = []
                }
            } else {
                this.currentAgriculturalTypesData = []
            }

            // 重置农资类型选择
            if (
                this.formData.materialId &&
                !this.currentAgriculturalTypesData.some((item) => item.value === this.formData.materialId)
            ) {
                this.formData.materialId = ''
            }
        },

        // 仓库选择变化处理
        onWarehouseChange(warehouseId) {
            // 清空仓库位置和农资类型选择
            this.formData.locationId = ''
            this.formData.materialId = ''
            this.currentAgriculturalTypesData = []
        },

        // 根据选择的规格设置specId
        updateSpecId() {
            const specMap = {
                '40kg/袋': 25827,
                '20kg/袋': 25828,
                '1L/瓶': 25829,
            }
            // 从规格选择的text中获取对应的ID
            const selectedSpec = this.specificationData.find(item => item.value === this.formData.specification)
            if (selectedSpec) {
                this.formData.specId = specMap[selectedSpec.text] || 25827
            }
        },

        submitForm() {
            console.log(this.formData)
            // 使用uni-forms的验证方法
            this.$refs.form
                .validate()
                .then((result) => {
                    console.log('验证结果', result)
                    this.submitFormData()
                })
                .catch((errors) => {
                    console.log('表单错误信息：', errors)
                })
        },

        async submitFormData() {
            try {
                // 从imageUploader组件获取最新的图片列表
                const imageList = this.$refs.imageUploader.getImageList()

                // 更新规格ID
                this.updateSpecId()

                // 构建提交的数据对象，映射到接口字段
                const submitData = {
                    materialId: this.formData.materialId,
                    specId: this.formData.specId,
                    warehouseId: this.formData.warehouseId,
                    locationId: this.formData.locationId,
                    quantity: parseFloat(this.formData.quantity) || 0,
                    unitPrice: parseFloat(this.formData.unitPrice) || 0,
                    totalAmount: parseFloat(this.formData.totalAmount) || 0,
                    batchNumber: this.formData.batchNumber || '',
                    supplier: this.formData.supplier || '',
                    operator: this.formData.operator || '',
                    procurementMethod: this.formData.procurementMethod || '', // 来源
                    inTime: this.formData.inDate, // 转换为ISO格式
                    remark: this.formData.remark || '',
                    images: imageList.join(','), // 转换为JSON格式
                }

                uni.showLoading({
                    title: '提交中...',
                })

                // 调用真实的API创建农资入库记录
                const res = await warehouse.createWarehouseIn(submitData)

                if (res.code === 0) {
                    uni.hideLoading()
                    uni.showToast({
                        title: '添加成功',
                        icon: 'success',
                        duration: 2000,
                        success: () => {
                            setTimeout(() => {
                                // 返回上一页并刷新
                                uni.navigateBack({
                                    delta: 1,
                                })
                            }, 1500)
                        },
                    })
                } else {
                    throw new Error(res.msg || '提交失败')
                }
            } catch (error) {
                uni.hideLoading()
                console.error('提交数据失败:', error)
                uni.showToast({
                    title: error.message || '提交失败，请重试',
                    icon: 'none',
                    duration: 2000,
                })
            }
        },
    },
}
</script>

<style lang="scss" scoped>

</style>
